<?php
/**
 * Created by PhpStorm.
 * User: 任旭明 <846723340@qq.com>
 * Date: 2018/10/22
 * Time: 16:10
 */

namespace app\model;

use think\Db;
use think\Log;
use think\cache\driver\Redis;
use app\index\controller\Signed;

class OrderModel extends BaseModel
{
    protected $table = 'sy_order';

    protected $length = 6;


    /**
     * @var 单价购买
     */
    final public function createOrder($order, $info, $coupon, $express_name, $orderNum)
    {
        Db::startTrans();
        try {
        $this->table .= '_' . substr($info['ouid'], -1, 1);
        // 插入订单
        // 最终价
        $order['deal_price'] = ($order['deal_price'] * 100 - $coupon['couponPrice'] * 100 + $express_name['express_price'] * 100) / 100;
        $order['express_name'] = $express_name['express_name'];
        $order['express_price'] = $express_name['express_price'];
        $oId = Db::table($this->table)->insertGetId($order);
            $salesSql = "update sy_product set  sales_me = CASE id ";
            $stockSql = 'UPDATE sy_product_info SET stock = CASE id ';
            foreach ($info['goods'] as $k => $v) {
                if (empty($insertSql)) {
                    $insertSql = "insert into `sy_order_info" . "_" . substr($info['ouid'], -1, 1) . "` (`order_id`, `ouid`, `pid`, `num`, `gid`, `oprice`) values ({$oId}, {$info['ouid']}, {$v['pid']}, {$v['num']}, {$v['gid']},{$v['oprice']})";
                } else {
                    $insertSql .= ",  ({$oId}, {$info['ouid']}, {$v['pid']}, {$v['num']}, {$v['gid']}, {$v['oprice']})";
                }
                $salesSql .= sprintf(" WHEN %d THEN %s ", $v['gid'], "`sales_me` + {$v['num']}");
                $stockSql .= sprintf(" WHEN %d THEN %s ", $v['pid'], "`stock` - {$v['num']}");
            }
            $stockIds = implode(',', array_column($info['goods'], 'pid'));
            $salesIds = implode(',', array_column($info['goods'], 'gid'));
            $salesSql .= " END WHERE id IN ({$salesIds})";
            $stockSql .= " END WHERE id IN ({$stockIds})";
            // 插入订单信息 减库存 加销量
            Db::execute($insertSql);
            Db::execute($stockSql);
            Db::execute($salesSql);
            // 加入积分
            $sql = "update `sy_user` set `intergral`= `intergral`+ " . (int)($order['deal_price'] / 10) . ", `experience` = `experience` +  " . (int)($order['deal_price'] / 10) . ", `signed` = unix_timestamp(now())  where `id` =  {$order['uid']}";
            Db::execute($sql);
            Db::name('sy_signed')->insert(['uid' => $order['uid'], 'signed_time' => time(), 'sign_time' => date('Y-m-d', time()), 'number' => (int)($order['deal_price'] / 10), 'status' => 2]);
            // 删除优惠券
            if ($coupon) {
                Db::name('sy_coupon')->delete($coupon);
            }
            Db::commit();
            (new Redis())->rm($orderNum);
        } catch (\Exception $e) {
            //回滚事务 记录日志
            Log::error($e);
            (new Redis())->set('error' . $orderNum, (new Redis())->get($orderNum));
            Db::rollback();
            return false;
        }
        return true;
    }

    final public function getOrder($condition, $field)
    {
        try {
            $list = Db::name($this->table)
                ->alias($this->check['as'])
                ->where($condition)
                ->join($this->check['joinTable'], $this->check['joinWhere'], $this->check['join'])
                ->join('sy_product_info pi', 'pi.id = oi.pid')
                ->field($field)
                ->limit($this->check['offset'], $this->check['length'])
                ->order($this->check['order'])
                ->select();
        } catch (\Exception $e) {
            throw (new \Exception('service error', 500));
        }
        return $list;
    }
}